﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Techdays2013.Models;
using Techdays2013.Helpers;

using SamuelBlanchard.Extenders;

namespace Techdays2013
{
    public partial class ControlsPage : PhoneApplicationPage
    {
        public ControlsPage()
        {
            InitializeComponent();

            ContactsList.IsGroupingEnabled = false;
            ContactsList.ItemsSource = DataService.LoadContacts();

            var personnages = from item in DataService.LoadPersonnages()
                              orderby item.Maison
                              group item by item.Maison into personnageByMaison
                              select new KeyedList<string, Personnage>(personnageByMaison);

            PersonnagesList.ItemsSource = new List<KeyedList<string, Personnage>>(personnages);

            this.Loaded += TextToSpeechPage_Loaded;
            this.BackKeyPress += TextToSpeechPage_BackKeyPress;
            this.GridFade.Visibility = System.Windows.Visibility.Visible;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        void TextToSpeechPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            this.GridFade.Visibility = System.Windows.Visibility.Visible;
            this.GridFade.FadeIn((s) => { NavigationService.GoBack(); });
        }

        /// <summary>
        /// On attent sue tout soit mise à jour
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        void TextToSpeechPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.GridFade.FadeOut((s) => { s.Visibility = Visibility.Collapsed; });
        }

        /// <summary>
        /// Switch
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void ToggleSwitch_Checked(object sender, RoutedEventArgs e)
        {
            ContactsList.IsGroupingEnabled = true;

            var contacts = AlphaKeyGroup<Contact>.CreateGroups(DataService.LoadContacts(),
                System.Threading.Thread.CurrentThread.CurrentUICulture,
                (Contact item) => { return item.Prenom; }, true);

            ContactsList.ItemsSource = contacts;
        } 

        private void ToggleSwitch_Unchecked(object sender, RoutedEventArgs e)
        {
            ContactsList.IsGroupingEnabled = false;
            ContactsList.ItemsSource = DataService.LoadContacts();
        }


    }
}